/**
 * Created by ke.ouyang on 19/12/24
 * Email ke.ouyang@huilianyi.com
 */
import React from 'react';
import {connect} from 'react-redux';
import {messages} from 'share/common';
import 'styles/setting/work-calendar/work-calendar.scss';
import SlideFrame from 'components/slide-frame';
import workCalenderService from 'containers/setting/work-calendar/work-calendar.service';
import NewWorkCalendar from 'containers/setting/work-calendar/new-work-calendar';
import CustomCalendar from 'containers/setting/work-calendar/custom-calendar';
import {Button, Icon, message, Spin, Row, Col, Divider, Popconfirm} from 'antd';
import Info from 'components/info';
import Condition from 'components/condition';
import errorMessage from 'share/errorMessage';
const {If} = Condition;

class WorkCalendar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currentYear: 2020,
      attributes: [{
        title: messages('basic-11.key180')/*日历编码*/, dataIndex: 'calendarCode', render: text => text ? text : '-'
      }, {
        title: messages('basic-11.key181')/*日历名称*/, dataIndex: 'calendarName', render: text => text ? text : '-'
      }, {
        title: messages('basic-11.key182')/*优先级*/, dataIndex: 'priority', render: text => text ? text : '-'
      }, {
        title: messages('basic-11.key183')/*说明*/, dataIndex: 'description', render: text => text ? text : '-'
      }, {
        title: messages('basic-11.key184')/*适用人员*/, dataIndex: 'common',
        render: value => {
          const { calendarDetail } = this.state;
          return (
            value
              ? <span>{messages('common.all')/*全部*/}</span>
              : <span>{messages('basic-11.key185',{arg1: calendarDetail.userGroups&&calendarDetail.userGroups.length})/*共{arg1}个人员组*/}</span>
          )
        }
      }],
      calendarList: [],
      calendarDetail: {
        userGroups: []
      },
      listLoading: true,
      detailLoading: true,
      circlePosition: 12,
      isEditing: false,
      confirmLoading: false,
      disableConfirm: true
    };
  }

  componentWillMount() {
    this.initialCalendar();
  }

  //初始化日历 （获取日历列表，以及 列表详情）
  initialCalendar = (calendarCode, isDelete)=> {
    const { calendarDetail, calendarList, currentYear } = this.state;
    workCalenderService.getCalendarList().then((res)=> {
      if(calendarCode) {
        let indexNum = 0;
        res.data.map((item, index)=>{
          if(item.calendarCode === calendarCode) {
            indexNum = index;
          }
        });
        this.setState({
          calendarList: res.data,
          listLoading: false,
          circlePosition: 12 + indexNum*52*(isDelete ? 0 : 1)
        })
      } else {
        this.setState({
          calendarList: res.data,
          listLoading: false,
        })
      }
    }).catch((err)=> {errorMessage(err.response)});
    let params = {
      calendarCode: calendarDetail.calendarCode || 'DEFAULT',
      year: currentYear
    };
    if (calendarCode) {
      params.calendarCode = calendarCode;
    }
    workCalenderService.getCalendarDetail(params).then((res)=> {
      this.calendarRef.startRender(res.data);
      this.setState({
        calendarDetail: res.data,
        detailLoading: false,
      })
    })
  };

  //打开侧拉 编辑 日历头部信息
  openSlideFrame = (title, data) => {
    SlideFrame.open({
      title: title,
      afterClose: (result)=> {this.afterCloseSlide(result)},
      params: data,
      content: NewWorkCalendar,
      hasFooter: true
    }, this)
  };

  //侧拉关闭 刷新列表
  afterCloseSlide = (result) => {
    this.setState({
      isEditing: false,
      detailLoading: true,
      disableConfirm: true
    });
    this.calendarRef.setState({
      isEditing: false
    });
    this.initialCalendar(result);
  };

  //复制日历 打开侧拉
  copyCalendar = (record) => {
    this.openSlideFrame(messages('basic-11.key186')/*复制日历*/, {calendarCode: record.target.id});
  };

  //编辑日历头部信息 打开侧拉
  editCalendar = () => {
    const { calendarDetail } = this.state;
    this.openSlideFrame(messages('basic-11.key187')/*编辑日历*/, calendarDetail);
  };

  //删除日历
  deleteCalendar = () => {
    const { calendarDetail } = this.state;
    this.setState({
      listLoading: true,
      detailLoading: true
    });
    workCalenderService.deleteCalendarByID(calendarDetail.calendarId).then((res)=> {
      this.initialCalendar('DEFAULT', true);
      this.setState({
        isEditing: false,
        disableConfirm: true
      });
      this.calendarRef.setState({
        isEditing: false
      });
    })
  };

  //切换日历
  handleChangeCalendar = (record, index) => {
    const { calendarDetail, currentYear } = this.state;
    if(record.target.id === calendarDetail.calendarCode ) {
      return
    } else {
      this.setState({ detailLoading: true });
      let params = {
        calendarCode: record.target.id,
        year: currentYear
      };
      workCalenderService.getCalendarDetail(params).then((res)=> {
        this.calendarRef.startRender(res.data);
        this.setState({
          calendarDetail: res.data,
          detailLoading: false,
          circlePosition: 10 + index*48
        })
      })
    }
    this.calendarRef.setState({
      isEditing: false
    });
    this.setState({
      isEditing: false,
      disableConfirm: true
    });
  };

  //渲染左侧 日历 列表
  renderCalendarList = () => {
    const { calendarList, listLoading } = this.state;
    const { permission } = this.props;
    let disabled = permission && (!permission.currentMenuPermission.authPolicyAll || permission.currentMenu.operationType === 'R');
    return (
      <Spin spinning={listLoading}>
        {calendarList.map((item, index)=> {
          return (
            <div className="one-row">
              <Button onClick={(record)=>{
                this.handleChangeCalendar(record, index);
              }} id={item.calendarCode}>{item.calendarName}</Button>
              <div onClick={!disabled && this.copyCalendar} id={item.calendarCode} className={`${disabled ? 'copy-button-disabled' : 'copy-button'}`}>
                {messages('common.copy')/*复制*/}
              </div>
            </div>
          )
        })}
      </Spin>
    )
  };

  //编辑 日历详情
  editCalendarDays = () => {
    this.setState({
      isEditing: true
    });
    this.calendarRef.startEdit();
  };

  //取消编辑 日历详情
  cancelEdit = () => {
    this.setState({
      isEditing: false,
      detailLoading: true,
      disableConfirm: true
    });
    this.calendarRef.setState({
      isEditing: false
    });
    this.initialCalendar();
  };

  //确认编辑结果
  confirmCalendarDays = () => {
    const { currentYear } = this.state;
    const data = this.calendarRef.state.changeData;
    this.setState({
      confirmLoading: true
    });
    workCalenderService.updateCalendarDetailWithCalendarID(currentYear, data).then((res)=> {
      this.setState({
        confirmLoading: false,
        isEditing: false,
        detailLoading: true,
        disableConfirm: true
      });
      this.calendarRef.setState({
        isEditing: false
      });
      message.success(messages('basic-11.key152')/*更新成功*/);
      this.initialCalendar();
    }).catch((err)=> {
      this.setState({
        confirmLoading: false
      });
      message.error(err.data.message)
    })
  };

  //禁用 确认按钮
  disableConfirm = (disableConfirm) => {
    this.setState({
      disableConfirm
    })
  };

  render() {
    const { calendarDetail, attributes, detailLoading, circlePosition, currentYear, isEditing,
      confirmLoading, disableConfirm, calendarList } = this.state;
    const isNotDefault = calendarDetail.calendarCode && calendarDetail.calendarCode !== 'DEFAULT';
    const { permission } = this.props;
    let disabled = permission && (!permission.currentMenuPermission.authPolicyAll || permission.currentMenu.operationType === 'R');
    return (
      <div className="work-calendar">
        <Row gutter={5}>
          <Col span={5} className="left-contain">
            <If value={!!calendarList.length}>
              <div className="gray-line">
                <div className="line-circle" style={{top: circlePosition + 'px'}}></div>
              </div>
            </If>
            {this.renderCalendarList()}
          </Col>
          <Col span={19} className="right-contain">
            <div className="calendar-box">
              <div className="info-box">
                <Info loading={detailLoading} title={messages('basic-11.key188')/*工作日历*/} dataSource={calendarDetail} attributes={attributes}>
                  <If value={isNotDefault && !disabled}>
                    <Button onClick={this.editCalendar} type='primary'>{messages('common.edit')/*编辑*/}</Button>
                    <Popconfirm
                      onConfirm={e => this.deleteCalendar(e)}
                      placement="bottomRight"
                      title={messages('common.confirm.delete')/*确定要删除吗？*/}
                    >
                      <Button onClick={e => { e.stopPropagation() }}>{messages('common.delete')/*删除*/}</Button>
                    </Popconfirm>
                  </If>
                </Info>
              </div>
              <Divider/>
              <Spin spinning={detailLoading}>
                <div className="year-tips-box">
                  <div className='time-of-year'>
                    <Icon type="left" className="left" /><span className="year-title">
                    {messages('basic-11.key189',{arg1: currentYear})/*{arg1}年*/}
                    </span><Icon type="right" className="right" />
                    <span>
                      <If value={!isEditing && isNotDefault && !disabled}>
                        <Button onClick={this.editCalendarDays} type='primary'>{messages('common.edit')/*编辑*/}</Button>
                      </If>
                      <If value={isEditing && isNotDefault}>
                        <Button style={{marginRight: '8px'}}
                                loading={confirmLoading}
                                disabled={disableConfirm}
                                onClick={this.confirmCalendarDays}
                                type='primary'>{messages('basic-11.key122')/*确认*/}</Button>
                        <Button onClick={this.cancelEdit}>{messages('common.cancel')/*取消*/}</Button>
                      </If>
                    </span>
                  </div>
                  <div className="tips">
                    <div className="holiday-box" /><div className="tips-title">{messages('basic-11.key194')/*节假日*/}</div>
                    <div className="weekend-box" /><div className="tips-title">{messages('basic-11.key195')/*公休日*/}</div>
                    <div className="weekdays-box" /><div className="tips-title">{messages('basic-11.key192')/*工作日*/}</div>
                    <div className="tips-line">
                      <Icon type="info-circle-o" /><div className="tips-text">{messages('basic-11.key193')/*点击日期，可切换日期属性*/}</div>
                    </div>
                  </div>
                </div>
                <CustomCalendar disableConfirm={this.disableConfirm} onRef={ref => this.calendarRef = ref} data={calendarDetail}/>
              </Spin>
            </div>
          </Col>
        </Row>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    permission: state.main.currentMenuPermission
  }
}

export default connect(mapStateToProps)(WorkCalendar)
